﻿/// <summary>
/// https://leetcode-cn.com/problems/next-permutation/
/// </summary>
public class Solution
{
    public void NextPermutation(int[] nums)
    {
        if (nums.Length is 0 or 1)
            return;

        Dictionary<int, int> exchangeable = new Dictionary<int, int>();
        for (int i = nums.Length - 1; i >= 0; i--)
        {
            var current = nums[i];
            var linq = from ex in exchangeable
                       where ex.Value > current
                       select ex;
            if (linq.Any())
            {
                var max = linq.Max(ex => ex.Key);
                nums[i] = nums[max];
                nums[max] = current;

                var iPlus1 = i + 1;
                Array.Sort(nums, iPlus1, nums.Length - iPlus1);

                return;
            }
            exchangeable.Add(i, current);
        }

        Array.Sort(nums);
    }
}